<script setup>
import { ref,reactive, nextTick,onActivated,getCurrentInstance,onMounted, watch  } from 'vue'; 
import { useRoute,useRouter } from 'vue-router';
import { ElMessage,ElMessageBox  } from 'element-plus';
import { releaseMgmtPage,stopTask,delTask } from '@/api/Marketing/coupon.js'

const seachTable = ref(null);
const route = useRoute();
const router = useRouter();
const instance = getCurrentInstance();

// 新增编辑回退时候刷新列表
onActivated(()=>{
  let closeTagName = sessionStorage.getItem('closeTagName');
  if(closeTagName == 'CouponSendEdit'){ //编辑退回时
      seachTable.value.handlerSearch(); //刷新当前页
      
  }else if(closeTagName == 'CouponSendAdd' || closeTagName == 'CouponSendCopy'){ //新增退回时
      seachTable.value.initSearch(); //返回第一页并刷新
  }
  instance.proxy.$forceUpdate(); //重新渲染demo
  sessionStorage.removeItem('closeTagName'); //溢出缓存中的tag名
})
const formInline = ref([
    {
      type: "input",
      prop: "taskName",
      placeholder: "发放名称",
      label: "",
      model: "",
    },
    {
        type: "select",
        placeholder: "发放状态",
        label: '',
        prop: 'taskStatus',
        data:[
            {
                label:"未开始",
                value:0
            },
            {
                label:"发放中",
                value:1
            },
            {
                label:"已结束",
                value:2
            }
        ],
        model: "",
    },
    {
      type: "datePicker",
      prop: ["createStartTime", "createEndTime"],
      startPlaceholder: "创建开始时间",
      endPlaceholder: "创建结束时间",
      label: "",
      model: [],
    },
])

const btnLefts = ref([
    {
      label:'新增发放',
      type:'primary',
      show:()=>true,
      img:new URL("@/assets/icon/btn-add.png",import.meta.url),
      click:(row)=>{
        router.push({name:'CouponSendAdd'})
      }
    },
])
const btnRights = ref([
])

const tableConfig = ref([

    {
      prop: "taskName",
      label: "发放名称",
      type:"slot",
      slotName:'taskName',
      width:310
    },
    {
      prop: "remark",
      label: "备注名称",
      width:200
    },
    {
      prop: "taskType",
      label: "发放类型",
      width:100,
      format:(value)=>{
        return ["自动发放","主动领取"][value]
      }
    },
    {
      prop: "targetType",
      label: "发放对象",
      type:"slot",
      slotName:'targetType',
      width:200
    },
    {
      prop: "content",
      label: "发放内容",
      type:"slot",
      slotName:'content',
      width:300
    },
    {
      prop: "taskStatus",
      label: "状态",
      width:100,
      format:(value)=>{
        return ["未开始","发放中","已结束"][value]
      }
    },
    {
      prop: "taskDateType",
      label: "发放时间",
      width:400,
      format:(value,row)=>{
        if(row.taskType == 0){
          if(value == 0){
            return row.taskStartTime;
          }else{
            if(row.targetType != 2){
              return row.taskStartTime;
            }else{
              return [row.taskStartTime,row.taskEndTime].join("~");
            }
            
          }
        }else{
          return [row.taskStartTime,row.taskEndTime].join("~");
        }

      }
    },
    {
      prop: "result",
      label: "发放结果",
      width:100,
      format:(value)=>{
        if(((value??'') === '') || (value == '-'))return '-';
        if(value == 0){
          return '全部成功'
        }else{
          
          return `${ value }人失败`
        }
      }
    },

    {
      prop: "createTime",
      label: "创建时间",
      width:200
    },
    {
      type: "action",
      label: "操作",
      width: 320,
      btns: [
        {
          label: () => "复制",
          show:(row)=>{
            return true
          },
          click: async (row) => {
            router.push({name:'CouponSendCopy',query:{id:row.id}})
          },
        },
        {
          label: () => "编辑",
          type:"success",
          show:(row)=>{
            return row.taskStatus == 0;
          },    
          click: async (row) => {
            router.push({name:'CouponSendEdit',query:{id:row.id}})
          },
        },
        {
          label: () => "终止",
          type:"danger",
          show:(row)=>{
            return row.taskStatus == 0 || row.taskStatus == 1;
          },
          click: async (row) => {
            ElMessageBox(
                {
                    cancelButtonText: '取消',
                    type: 'warning',
                    title: '提示',
                    showCancelButton: true,
                    confirmButtonText:'终止',
                    confirmButtonClass:'el-button--danger',
                    message:"确定终止该发放？",
                    beforeClose: async (action, instance, done) => {
                        if (action === 'confirm') {
                            instance.confirmButtonLoading = true
                            instance.confirmButtonText = 'Loading...'
                            try{
                                await stopTask(row.id);
                                instance.confirmButtonLoading = false
                                done();
                                ElMessage.success('终止成功');
                                seachTable.value.handlerSearch();
                            }catch(e){
                                instance.confirmButtonLoading = false
                            }
                        } else {
                            done()
                        }
                    },
                }
            )
          },
        },
        {
          label: () => "删除",
          type:"danger",
          show:(row)=>{
            return row.taskStatus == 2;
          },
          click: async (row) => {
            ElMessageBox(
                {

                    cancelButtonText: '取消',
                    type: 'warning',
                    title: '提示',
                    showCancelButton: true,
                    confirmButtonText:'删除',
                    confirmButtonClass:'el-button--danger',
                    message:"确定删除该发放？",
                    beforeClose: async (action, instance, done) => {
                        if (action === 'confirm') {
                            instance.confirmButtonLoading = true
                            instance.confirmButtonText = 'Loading...'
                            try{
                                await delTask(row.id);
                                instance.confirmButtonLoading = false
                                done();
                                ElMessage.success('删除成功');
                                seachTable.value.initSearch();
                            }catch(e){
                                instance.confirmButtonLoading = false
                            }
                        } else {
                            done()
                        }
                    },
                }
            )
          },
        },
      ]
    }
]);
const tableLoading = ref(false)
const totalPage = ref(0)
const tableData = ref([]);


const handlerSearch = async (formInline)=>{
    tableLoading.value = true;
    try{
        let result = await releaseMgmtPage(formInline);
        totalPage.value = Number(result.total);
        tableData.value = result.records;

        tableLoading.value = false;
    }catch(e){
        tableLoading.value = false;
    }
}
const lookDetail = (id)=>{
  router.push({name:"CouponSendDetail",query:{id:id}})
}
</script>
<template>
    <div class="page-content">
        <SeachTable 
          :tableType="1"
          ref="seachTable"
          :forms="formInline"
          :btnLefts="btnLefts"
          :btnRights="btnRights"
          :tableLoading="tableLoading"
          :tableConfig="tableConfig"
          :tableData="tableData"
          :totalPage="totalPage"
          @handlerSearch="handlerSearch"
        >
            <template #taskName="{ row }">
                <div class="a-link" @click="lookDetail(row.id)">{{ row.taskName }}</div>
            </template>
            <template #targetType="{ row }">
              <div class="info-show" v-if="row.targetType == 0">
                  <span class="tip-show">
                      全部会员
                  </span>
                </div>
                <div class="info-show" v-if="row.targetType == 1">
                    <el-tooltip placement="top">
                        <template #content>
                            <div class="tips-info">
                              {{ row.targetObject?row.targetObject.join("、"):"-" }}
                            </div>
                        </template>
                        <span class="tip-show">
                          {{ row.targetObject?row.targetObject.join("、"):"-" }}
                        </span>
                    </el-tooltip>
                </div>
                <div class="info-show" v-if="row.targetType == 3">
                    <el-tooltip placement="top">
                        <template #content>
                            <div class="tips-info">
                              {{ row.targetObject?row.targetObject.join("、"):"-" }}
                            </div>
                        </template>
                        <span class="tip-show">
                          {{ row.targetObject?row.targetObject.join("、"):"-" }}
                        </span>
                    </el-tooltip>
                </div>
                <div class="info-show" v-if="row.targetType == 2">
                  <span class="tip-show">
                      新会员
                  </span>
                </div>
                <div class="info-show" v-if="row.targetType == 4">
                  <span class="tip-show">
                      指定会员
                  </span>
                </div>
            </template>
            <template #content="{ row }">
                <div class="info-show" v-if="row.content">
                    <el-tooltip placement="top">
                        <template #content>
                            <div class="tips-info">
                              {{ row.content }}
                            </div>
                        </template>
                        <span class="tip-show">
                          {{ row.content}}
                        </span>
                    </el-tooltip>
                </div>
                <span v-else>-</span>
            </template>
        </SeachTable>
    </div>
</template>
<style lang="less" scoped>
.tips-info{
    max-width: 300px; 
}
.info-show{
    width: 100%;
    display: flex;
    justify-content: flex-start;
    align-items: center;
    .tip-show{
        max-width: 100%;
        box-sizing:border-box;
        padding-right:4px;
        font-weight: 400;
        color: #222222;
        text-overflow: ellipsis;
        white-space: nowrap;
        overflow: hidden;
    }
    .text-show{
        max-width: calc(100% - 14px);
        box-sizing:border-box;
        padding-right:4px;
        font-weight: 400;
        color: #222222;
        line-height: 18px;
        word-break: break-all;
        word-wrap: break-word;
    }
    .img{
        width: 14px;
        height: 14px;
        cursor: pointer;

    }
}
.a-link{
    color:#3480FF;
    font-size: 14px;
    cursor: pointer;
}

</style>